package com.lookup.api.handler;

import com.google.common.net.HttpHeaders;
import com.google.common.net.MediaType;
import com.lookup.api.logger.LoggerWrapper;
import io.vertx.core.Handler;
import io.vertx.rxjava.core.MultiMap;
import io.vertx.rxjava.core.buffer.Buffer;
import io.vertx.rxjava.core.http.HttpServerRequest;
import io.vertx.rxjava.ext.web.RoutingContext;
import rx.Observable;

import java.util.Objects;


public abstract class AbstractHttpHandler<T> implements Handler<RoutingContext> {

    private LoggerWrapper logger = new LoggerWrapper(this.getClass().getName(), "$$");

    @Override
    public void handle(RoutingContext context) {
        HttpServerRequest req = context.request();
        MultiMap params = req.params();
        MultiMap headers = req.headers();
        handleInternal(context, req, headers, params)
                .subscribe(
                        result -> {
                            Buffer buffer = Buffer.buffer(Objects.toString(result));
                            context.response()
                                    .setStatusCode(200)
                                    .putHeader(HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8.toString())
                                    .putHeader(HttpHeaders.CONTENT_LENGTH, Objects.toString(buffer.length()))
                                    .putHeader(HttpHeaders.CONNECTION, "keep-alive")
                                    .write(buffer)
                                    .end();
                        },
                        error ->{ context.response().setStatusCode(500).end();logger.info("handleInternal  error",error); },
                        () ->logger.info("routing  complete"));
    }

    /**
     * @param event
     * @param req
     * @param headers
     * @param params
     */
    public abstract Observable<T> handleInternal(RoutingContext event,
                                                 HttpServerRequest req,
                                                 MultiMap headers,
                                                 MultiMap params);

}
